using Microsoft.AspNetCore.Mvc;
using WeatherApp.Models;
using WeatherApp.Services;

namespace WeatherApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WeatherController : ControllerBase
    {
        private readonly IWeatherService _weatherService;
        private readonly IDataService _dataService;
        private readonly ILogger<WeatherController> _logger;

        public WeatherController(
            IWeatherService weatherService, 
            IDataService dataService,
            ILogger<WeatherController> logger)
        {
            _weatherService = weatherService;
            _dataService = dataService;
            _logger = logger;
        }

        /// <summary>
        /// 获取当前天气信息
        /// </summary>
        /// <param name="city">城市名称</param>
        /// <returns>当前天气信息</returns>
        [HttpGet("current/{city}")]
        public async Task<ApiResponse<WeatherInfo>> GetCurrentWeather(string city)
        {
            try
            {
                var weather = await _weatherService.GetCurrentWeatherAsync(city);
                
                // 添加搜索历史（使用默认用户ID）
                await _dataService.AddSearchHistoryAsync("default", city);
                
                return new ApiResponse<WeatherInfo>
                {
                    Success = true,
                    Message = "获取天气信息成功",
                    Data = weather
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取当前天气失败: {City}", city);
                return new ApiResponse<WeatherInfo>
                {
                    Success = false,
                    Message = "获取天气信息失败",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取天气预报
        /// </summary>
        /// <param name="city">城市名称</param>
        /// <returns>5天天气预报</returns>
        [HttpGet("forecast/{city}")]
        public async Task<ApiResponse<WeatherForecast>> GetForecast(string city)
        {
            try
            {
                var forecast = await _weatherService.GetWeatherForecastAsync(city);
                return new ApiResponse<WeatherForecast>
                {
                    Success = true,
                    Message = "获取天气预报成功",
                    Data = forecast
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气预报失败: {City}", city);
                return new ApiResponse<WeatherForecast>
                {
                    Success = false,
                    Message = "获取天气预报失败",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取生活指数
        /// </summary>
        /// <param name="city">城市名称</param>
        /// <returns>生活指数信息</returns>
        [HttpGet("life-index/{city}")]
        public async Task<ApiResponse<List<LifeIndex>>> GetLifeIndex(string city)
        {
            try
            {
                var indices = await _weatherService.GetLifeIndexAsync(city);
                return new ApiResponse<List<LifeIndex>>
                {
                    Success = true,
                    Message = "获取生活指数成功",
                    Data = indices
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生活指数失败: {City}", city);
                return new ApiResponse<List<LifeIndex>>
                {
                    Success = false,
                    Message = "获取生活指数失败",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 搜索城市
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <returns>匹配的城市列表</returns>
        [HttpGet("search-cities")]
        public async Task<ApiResponse<List<CityInfo>>> SearchCities([FromQuery] string keyword)
        {
            try
            {
                var cities = await _weatherService.SearchCitiesAsync(keyword);
                return new ApiResponse<List<CityInfo>>
                {
                    Success = true,
                    Message = "搜索城市成功",
                    Data = cities
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索城市失败: {Keyword}", keyword);
                return new ApiResponse<List<CityInfo>>
                {
                    Success = false,
                    Message = "搜索城市失败",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 根据坐标获取城市信息
        /// </summary>
        /// <param name="latitude">纬度</param>
        /// <param name="longitude">经度</param>
        /// <returns>城市信息</returns>
        [HttpGet("city-by-location")]
        public async Task<ApiResponse<CityInfo>> GetCityByLocation([FromQuery] double latitude, [FromQuery] double longitude)
        {
            try
            {
                var city = await _weatherService.GetCityByLocationAsync(latitude, longitude);
                return new ApiResponse<CityInfo>
                {
                    Success = true,
                    Message = "获取城市信息成功",
                    Data = city
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据坐标获取城市失败: {Latitude}, {Longitude}", latitude, longitude);
                return new ApiResponse<CityInfo>
                {
                    Success = false,
                    Message = "获取城市信息失败",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取完整的天气信息（当前天气 + 预报 + 生活指数）
        /// </summary>
        /// <param name="city">城市名称</param>
        /// <returns>完整的天气信息</returns>
        [HttpGet("complete/{city}")]
        public async Task<ApiResponse<object>> GetCompleteWeather(string city)
        {
            try
            {
                var currentWeather = await _weatherService.GetCurrentWeatherAsync(city);
                var forecast = await _weatherService.GetWeatherForecastAsync(city);
                var lifeIndices = await _weatherService.GetLifeIndexAsync(city);

                var result = new
                {
                    currentWeather,
                    forecast,
                    lifeIndices
                };

                return new ApiResponse<object>
                {
                    Success = true,
                    Message = "获取完整天气信息成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取完整天气信息失败: {City}", city);
                return new ApiResponse<object>
                {
                    Success = false,
                    Message = "获取完整天气信息失败",
                    Data = null
                };
            }
        }

        [HttpGet("history/{city}")]
        public async Task<ApiResponse<List<WeatherRecord>>> GetWeatherHistory(string city, [FromQuery] int days = 7)
        {
            try
            {
                var history = await _dataService.GetWeatherHistoryAsync(city, days);
                return new ApiResponse<List<WeatherRecord>>
                {
                    Success = true,
                    Message = "获取天气历史成功",
                    Data = history
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气历史失败: {City}", city);
                return new ApiResponse<List<WeatherRecord>>
                {
                    Success = false,
                    Message = "获取天气历史失败",
                    Data = null
                };
            }
        }

        [HttpGet("recent-records")]
        public async Task<ApiResponse<List<WeatherRecord>>> GetRecentRecords([FromQuery] int count = 10)
        {
            try
            {
                var records = await _dataService.GetRecentWeatherRecordsAsync(count);
                return new ApiResponse<List<WeatherRecord>>
                {
                    Success = true,
                    Message = "获取最近天气记录成功",
                    Data = records
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取最近天气记录失败");
                return new ApiResponse<List<WeatherRecord>>
                {
                    Success = false,
                    Message = "获取最近天气记录失败",
                    Data = null
                };
            }
        }
    }
} 